import { createSlice } from "@reduxjs/toolkit";
import { request ,getToken,setToken as _setToken} from "@/utils";
import { removeToken } from "@/utils/token";

const userStore=createSlice({
    name:'user',
    initialState:{
        token:getToken()||'',
        userInfo:{}
    },
    reducers:{
        setToken(state,action){
            state.token=action.payload
            _setToken(action.payload)
        },
        setUserInfo(state,action){
            state.userInfo=action.payload
        },
        clearUserInfo(state){
            state.userInfo={}
            state.token=""
            removeToken()
        }
    }
})

//异步代码
const fetchLogin=(loginForm)=>{
    return async(dispatch)=>{
        const res=await request.post('/authorizations',loginForm)
        dispatch(setToken(res.data.token))
    }
}

//获取个人信息
const fetchUserInfo=()=>{
    return async(dispatch)=>{
        const res=await request.get('/user/profile')
        dispatch(setUserInfo(res.data))
    }
}

const userReducer=userStore.reducer

const {setToken,setUserInfo,clearUserInfo}=userStore.actions

export {setToken,fetchLogin,fetchUserInfo,clearUserInfo}

export default userReducer